#!/bin/env bash

alias_es() {
    if [ ! -d "$1"/es ]; then
        echo "alias es"
        ln -s "$1"/elasticsearch* "$1"/es
    fi
}

mk_mysql_dir() {
    echo "make es dirs"
    mkdir -p "$1"/es-data
}

add_es_usr() {
    if [ "" == "$(awk -F ":" '{print $1}' /etc/passwd | grep ^es)" ]; then
        echo "add es user"
        useradd es
    fi
}

change_own() {
    echo "chown dir to es"
    chown -R es.es "$1"/*
}

backup_es_yml() {
    if [ ! -f "$1"/es/config/elasticsearch.yml.bak ]; then
        echo "backup es yml"
        mv "$1"/es/config/elasticsearch.yml "$1"/es/config/elasticsearch.yml.bak
    fi
}

ip=$(ip addr show | grep "inet 192.168.1.*" | awk -F '[ /]+' '{print $3}')
last=$(echo "${ip}" | awk -F "." '{print $4}')

rewrite_elasticsearch_yml() {
    echo "rewrite elasticsearch.yml"
    cat <<EOF >"$1"/es/config/elasticsearch.yml
cluster.name: my-application
node.name: node-ip-${ip}
path.data: $1/es-data
bootstrap.memory_lock: true
network.host: ${ip}
http.port: 92${last}
discovery.zen.ping.unicast.hosts: ["$2","$3"]
discovery.zen.minimum_master_nodes: 2
EOF
}

change_file_desc() {
    if [ "65535" != "$(ulimit -n)" ]; then
        ulimit -n 65535
        {
            echo "* soft nofile 65535"
            echo "* hard nofile 65535"
        } >>/etc/security/limits.conf
    fi

}

change_max_map_count() {
    if [ "" == "$(cat /etc/sysctl.conf | grep ^vm)" ]; then
        sysctl -w vm.max_map_count=262144
        echo "vm.max_map_count=262144" >>/etc/sysctl.conf
        sysctl -p
    fi
}

start_es() {
    "$1"/es/bin elasticsearch -d
}

kill_es(){
    pid=$(jps | grep Elasticsearch | awk '{print $1}')
    kill -SIGTERM "${pid}"
}


setup_es() {
    echo "setup es"
    alias_es "$1"
    mk_mysql_dir "$1"
    add_es_usr
    change_own "$1"
    backup_es_yml "$1"
    rewrite_elasticsearch_yml "$1" "$a" "$b"
    change_file_desc
    change_max_map_count
}


usage() {
    echo "useage:"
    echo "-h help"
    echo "-e path of elasticsearch,cluster ip xx.xx xx.xx"
    exit 0
}

while getopts 'he:a:b:' OPT; do
    case $OPT in
    a) a="$OPTARG" ;;
    b) b="$OPTARG" ;;
    e) setup_es "$OPTARG" ;;
    h) usage ;;
    ?) usage ;;
    esac
done


